import { Button, Upload, Icon } from 'antd';
import { connect } from 'dva';
import React from 'react';

@connect(({ global }) => ({ token: global.uploadToken }))
class VideoUploader extends React.Component {
  state = { fileName: null };

  handleChange = ({ file }) => {
    const { onChange } = this.props;
    if (file.status === 'done') {
      this.setState({ fileName: file.name });
      onChange(file.response.hash);
    }
  };

  beforeUpload = () => {
    const { dispatch } = this.props;
    return new Promise(async resolve => {
      await dispatch({ type: 'global/updateUploadToken' });
      resolve();
    });
  };

  render() {
    const { token } = this.props;
    const { fileName } = this.state;
    return (
      <div>
        <Upload
          action="https://up.qiniup.com"
          data={{ token }}
          beforeUpload={this.beforeUpload}
          showUploadList={false}
          onChange={this.handleChange}
        >
          <Button>
            <Icon type="upload" />
            上传视频
          </Button>
        </Upload>
        <br />
        <h6>{fileName ? `当前文件为：${fileName}` : ''}</h6>
      </div>
    );
  }
}

export default VideoUploader;
